

package com.hazelcast.jet.impl.processor;

import com.hazelcast.jet.Traverser;
import com.hazelcast.jet.core.AbstractProcessor;
import com.hazelcast.jet.core.Inbox;

import javax.annotation.Nonnull;
import java.util.function.Function;

/**
 * Processor which exploits natural batching of {@link Inbox} items. For
 * each received batch of items it emits all the items from the traverser
 * returned by the given itemList-to-traverser function.
 *
 * @param <T> received item type
 * @param <R> emitted item type
 */
public class TransformBatchedP<T, R> extends AbstractProcessor {

    private final Function<? super Iterable<T>, ? extends Traverser<? extends R>> mapper;

    private Traverser<? extends R> outputTraverser;

    public TransformBatchedP(Function<? super Iterable<T>, ? extends Traverser<? extends R>> mapper) {
        this.mapper = mapper;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void process(int ordinal, @Nonnull Inbox inbox) {
        if (outputTraverser == null) {
            outputTraverser = mapper.apply((Iterable<T>) inbox);
        }

        if (emitFromTraverser(outputTraverser)) {
            inbox.clear();
            outputTraverser = null;
        }
    }

    @Override
    public boolean closeIsCooperative() {
        return true;
    }
}
